package tool

import (
	"context"
	//	"encoding/json"

	. "gitee.com/liukexing/isrn/api"
)

type ConfigCommand struct {
	Shell
}

/*
USAGE
  ipfs config <key> [<value>] - Get and set ipfs config values.

SYNOPSIS
  ipfs config [--bool] [--json] [--] <key> [<value>]

ARGUMENTS

  <key>     - The key of the config entry (e.g. "Addresses.API").
  [<value>] - The value to set the config entry to.

OPTIONS

  --bool bool - Set a boolean value. Default: false.
  --json bool - Parse stringified JSON. Default: false.

DESCRIPTION

  'ipfs config' controls configuration variables. It works
  much like 'git config'. The configuration values are stored in a config
  file inside your IPFS repository.

  Examples:

  Get the value of the 'Datastore.Path' key:

    $ ipfs config Datastore.Path

  Set the value of the 'Datastore.Path' key:

    $ ipfs config Datastore.Path ~/.ipfs/datastore

SUBCOMMANDS
  ipfs config edit           - Open the config file for editing in $EDITOR.
  ipfs config replace <file> - Replace the config with <file>.
  ipfs config show           - Output config file contents.

  Use 'ipfs config <subcmd> --help' for more information about each command.
*/

type ConfigValue struct {
	Key   string
	Value interface{}
}

func (s *ConfigCommand) ConfigSet(key, value string, isjson bool) (*ConfigValue, error) {
	cmdargs := []string{key, value}

	out := &ConfigValue{}
	err := s.Request("config", cmdargs...).Option("json", isjson).Exec(context.Background(), out)
	if err != nil {
		return nil, err
	}
	return out, nil

	//	req := s.NewRequest(context.Background(), "config", cmdargs...)
	//	if isjson {
	//		req.Opts["json"] = "true"
	//	}

	//	resp, err := req.Send(s.HttpCli)
	//	if err != nil {
	//		return nil, err
	//	}
	//	defer resp.Close()

	//	if resp.Error != nil {
	//		return nil, resp.Error
	//	}
	//	out := &ConfigValue{}
	//	err = json.NewDecoder(resp.Output).Decode(out)
	//	if err != nil {
	//		return nil, err
	//	}

	//	return out, nil
}

func (s *ConfigCommand) ConfigGet(key string) (*ConfigValue, error) {
	cmdargs := []string{key}

	out := &ConfigValue{}
	err := s.Request("config", cmdargs...).Exec(context.Background(), out)
	if err != nil {
		return nil, err
	}
	return out, nil

	//	req := s.NewRequest(context.Background(), "config", cmdargs...)

	//	resp, err := req.Send(s.HttpCli)
	//	if err != nil {
	//		return nil, err
	//	}
	//	defer resp.Close()

	//	if resp.Error != nil {
	//		return nil, resp.Error
	//	}
	//	out := &ConfigValue{}
	//	err = json.NewDecoder(resp.Output).Decode(out)
	//	if err != nil {
	//		return nil, err
	//	}

	//	return out, nil
}
